package com.hawthorn.redis.service.appuser.impl;

import com.hawthorn.component.constant.RedisConstant;
import com.hawthorn.component.utils.common.StrMyUtil;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.platform.utils.common.MyUtil;
import com.hawthorn.redis.repository.AppUserCacheMapper;
import com.hawthorn.redis.service.appuser.AppUserCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>todo 加载App用户缓存服务实现类</p>
 * @author: andyten@tom.com | xukaixing@hotmail.com
 * @created: 2021/11/11 8:48 PM
 * @version v1.0.3
 * @copyright: Copyright (c)  andyten
 */
@Service
@Slf4j
public class AppUserCacheServiceImpl implements AppUserCacheService
{
  @Autowired
  RedisMyClient redisMyClient;

  @Resource
  private AppUserCacheMapper appUserCacheMapper;

  /**
   * <p>todo 初始化方法</p>
   * @param:
   * @return: void
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/11/11 8:48 PM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/11/11    andy.ten        v1.0.1             init
   */
  @Transactional(readOnly = true)
  public void init()
  {
    List<Map<String, Object>> userCache = appUserCacheMapper.selectAppUser();
    String key;
    // todo 先删除redis中的key
    redisMyClient.removeAll(StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_APPUSER_PREFIX, "*"));
    for (Map user : userCache)
    {
      key = StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_APPUSER_PREFIX, MyUtil.getValue(user.get("login_code")));
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_APPUSER_LOGINCODE, MyUtil.getValue(user.get("login_code")));
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_APPUSER_PHONE, MyUtil.getValue(user.get("phone")));
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_APPUSER_USERNAME, MyUtil.getValue(user.get("user_name")));
      redisMyClient.hSet(key, RedisConstant.REDIS_KEY_APPUSER_OPENID, MyUtil.getValue(user.get("open_id")));
    }
    log.info("====== load appuserdata to redis success ======");
  }


}
